<?php
/**
 * 数据库核心操作类
 * @author Wj
 */
namespace jun;

use Exception;
use Mysqli;

class Db
{
    // 数据库 host
    // 本类的对象实力
    private static $_instance;
    // 保存数据库实例
    private $db;
    // 数据库地址
    private static $host='127.0.0.1';
    // 数据库登录账号
    private static $uname='root';
    // 数据库登录密码
    private static $pwd='root';
    // 数据库名称
    private static $dbname='dbname';
    // 数据库端口
    private static $port=3306;
    // 字符编码
    private static $charset='utf8';


    private function __construct(){
        $this->connect();        
    }

    private function connect(){
        $this->db = new Mysqli(self::$host,self::$uname,self::$pwd,self::$dbname,self::$port);
        $this->db->set_charset(self::$charset);
        if($this->db->errno){
            $this->outputError("Mysql Errno : {$this->db->errno}; Info : {$this->db->error}",$this->db->errno);
        }
    }

    public function static init(){
        if (!(self::$_instance instanceof self) || self::$_instance == false) {       
            self::$_instance = new self;
        }
        return self::$_instance;
    }

    public function query(){
        if($this->ping()){
            $query = $this->db->query($sql);
        }else{
            $this->close(); // 释放                         
            $this->connect(); // 重连                               
            // echo "启动断线重连机制\n";
            $query = $this->db->query($sql);
        }
        return $query;
    }
    public function insertId(){
        return $this->db->insert_id;
    }
    public function close(){
        $this->db->close();
    }

    /**
        * 构造事物
        */
    public function autocommit(){
        $this->db->autocommit(false);
    }
    /**
        * 提交事物
        */
    public function commit(){
        $this->db->commit();
    }
    /**
        * 关闭事物
        */
    public function rollback(){
        $this->db->rollback();
    }

    /**
        * 检测数据库实例是否有效
        */
    public function ping(){
            return $this->db->ping();
    }

    private function outputError($errorMsg,$errno){
        throw new Exception($errorMsg,$errno);
    }
}
